//
//  YDBScanBluViewController.swift
//  DKE-Album
//
//  Created by dagny on 2025/9/20.
//  Copyright © 2025 杨东宝. All rights reserved.
//

import Foundation
import UIKit

import UIKit

class TimePickerViewController: YDBBaseViewController {
    // 回调闭包
    var onTimeSelected: ((Bool,Int, Int, Int) -> Void)?
    private var timePicker: CustomTimePickerView!
    
    var hour: Int! = 05
    var minute: Int! = 05
    var second: Int! = 05
    var isRepeat: Bool = false
    
    lazy var tipLabe: UILabel = {
        let label = UILabel()
        label.text = "repeatTip".localized
        label.textColor = .gray
        label.font = DIMENSION_FONT_OF_SIZE(20)
        return label
    }()
    lazy var confirmBtn: UIButton = {
        let button = UIButton(type: .custom)
        button.setTitle("confirm".localized, for: .normal)
        button.setTitleColor(HexRGB(0xffffff), for: .normal)
        button.layer.cornerRadius = 20
        button.layer.masksToBounds = true;
        button.setBackgroundColor(HexRGB(0x3d4466), forState: .normal)
        button.titleLabel?.font = DIMENSION_FONT_OF_SIZE(14)
        button.addTarget(self, action: #selector(confirmBtnClick(_ : )), for: .touchUpInside)
        return button
    }()
    lazy var backView: UIView = {
        let view = UIView()
        view.backgroundColor = HexRGB(0xEEEEEE)
        view.alpha = 0.3
        return view
    }()
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
    }
    private func setupUI() {
        view.backgroundColor = .white
        // 创建时间选择器
        timePicker = CustomTimePickerView(frame: CGRect(x:0,y: 1.5 * kTopHeight,width:kScreenWidth, height: kScreenHeight - kTopHeight*4))
        timePicker.onTimeChanged = { [weak self] hour, minute, second in
            self?.hour = hour
            self?.minute = minute
            self?.second = second
        }
        view.addSubview(timePicker)
        view.addSubview(backView)
        view.addSubview(self.confirmBtn)
        confirmBtn.frame =  CGRect(x:DIMENSION_VALUE(20),y: kScreenHeight - 2*kTopHeight , width:kScreenWidth - DIMENSION_VALUE(40), height:DIMENSION_VALUE(40))
        backView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.top.equalTo(timePicker.snp_top)
            make.bottom.equalTo(timePicker.snp_bottom)
        }
        let switchControl = UISwitch()
        switchControl.onTintColor = HexRGB(0x3D4466)
        switchControl.thumbTintColor = UIColor.white
           // 添加阴影效果
        switchControl.layer.shadowColor = UIColor.black.cgColor
        switchControl.layer.shadowOffset = CGSize(width: 0, height: 2)
        switchControl.layer.shadowOpacity = 0.3
        switchControl.layer.shadowRadius = 3
        switchControl.addTarget(self, action: #selector(switchValueChanged(_:)), for: .valueChanged)
        view.addSubview(switchControl)
        view.addSubview(self.tipLabe)
        switchControl.snp.makeConstraints { make in
            make.right.equalToSuperview().offset(DIMENSION_VALUE(-20))
            make.top.equalToSuperview().offset(0.5*kTopHeight)
        }
        self.tipLabe.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(DIMENSION_VALUE(20))
            make.centerY.equalTo(switchControl.snp_centerY)
        }
        backView.isHidden = switchControl.isOn
        // 设置初始时间
        timePicker.setTime(hour: self.hour, minute: self.minute, second: self.second)
    }
    @objc func switchValueChanged(_ sender: UISwitch) {
        isRepeat = sender.isOn
        backView.isHidden = sender.isOn
    }
    @objc func confirmBtnClick(_ btn :UIButton) {
        self.onTimeSelected?(isRepeat,hour,minute,second)
        navigationController?.popViewController(animated: true)
    }
}

// 自定义时间选择器控件
class CustomTimePickerView: UIView {
    
    // MARK: - 属性
    private var hours: [String] = []
    private let minutes: [String] = Array(0...59).map { String(format: "%02d", $0) }
    private let seconds: [String] = Array(0...59).map { String(format: "%02d", $0) }
    
    private var hourScrollView: UIScrollView!
    private var minuteScrollView: UIScrollView!
    private var secondScrollView: UIScrollView!
    
    private var hourLabels: [UILabel] = []
    private var minuteLabels: [UILabel] = []
    private var secondLabels: [UILabel] = []
    
    private var hourUnitLabel: UILabel!
    private var minuteUnitLabel: UILabel!
    private var secondUnitLabel: UILabel!
    
    private let rowHeight: CGFloat = DIMENSION_VALUE(60)
    private let visibleRows = 5 // 可见行数（奇数，以便中间行是选中行）
    
    var selectedHour: Int = 05
    var selectedMinute: Int = 05
    var selectedSecond: Int = 05
    
    var onTimeChanged: ((Int, Int, Int) -> Void)?
    
    // MARK: - 初始化
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupData()
        setupUI()
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        setupData()
        setupUI()
    }
    
    private func setupData() {
        // 小时数据：0-99 + "不限"选项
        hours = Array(0...99).map { String(format: "%02d", $0) }
    }
    
    private func setupUI() {
         backgroundColor = HexRGB(0xFEFEFE)
        // 计算每列的宽度
        let columnWidth = bounds.width / 3

        // 创建滚动视图
        hourScrollView = createScrollView(x: 0, width: columnWidth)
        minuteScrollView = createScrollView(x: columnWidth, width: columnWidth)
        secondScrollView = createScrollView(x: columnWidth * 2, width: columnWidth)
        
        // 添加标签到滚动视图
        addLabels(to: hourScrollView, data: hours, labelsArray: &hourLabels)
        addLabels(to: minuteScrollView, data: minutes, labelsArray: &minuteLabels)
        addLabels(to: secondScrollView, data: seconds, labelsArray: &secondLabels)
        
        // 创建单位标签（只在选中行显示）
        hourUnitLabel = createUnitLabel(text: "时")
        minuteUnitLabel = createUnitLabel(text: "分")
        secondUnitLabel = createUnitLabel(text: "秒")
        
        // 设置初始位置
        setInitialSelection()
    }
    
    private func createScrollView(x: CGFloat, width: CGFloat) -> UIScrollView {
        let scrollView = UIScrollView(frame: CGRect(x: x, y: 0, width: width, height: bounds.height))
        scrollView.delegate = self
        scrollView.showsVerticalScrollIndicator = false
        scrollView.showsHorizontalScrollIndicator = false
        scrollView.decelerationRate = UIScrollView.DecelerationRate.fast
        addSubview(scrollView)
        
        return scrollView
    }
    
    private func addLabels(to scrollView: UIScrollView, data: [String], labelsArray: inout [UILabel]) {
        let contentHeight = CGFloat(data.count) * rowHeight
        scrollView.contentSize = CGSize(width: scrollView.bounds.width, height: contentHeight)
        
        // 添加顶部填充（使中间行成为默认选中行）
        let topInset = (scrollView.bounds.height - rowHeight) / 2
        scrollView.contentInset = UIEdgeInsets(top: topInset, left: 0, bottom: topInset, right: 0)
        
        for (index, value) in data.enumerated() {
            let label = UILabel(frame: CGRect(x: 0, y: CGFloat(index) * rowHeight, width: scrollView.bounds.width, height: rowHeight))
            label.text = value
            label.textAlignment = .center
            label.font = UIFont.systemFont(ofSize: 18, weight: .regular)
            label.textColor = .darkGray
            scrollView.addSubview(label)
            labelsArray.append(label)
        }
    }
    
    private func createUnitLabel(text: String) -> UILabel {
        let label = UILabel()
        label.text = text
        label.textAlignment = .left
        label.font = DIMENSION_FONT_OF_SIZE(18)
        label.textColor = HexRGB(0x3d4466)
        label.isHidden = true // 初始隐藏
        addSubview(label)
        return label
    }
    private func setInitialSelection() {
        // 设置初始选择位置
        setScrollViewPosition(hourScrollView, index: 05, animated: false)
        setScrollViewPosition(minuteScrollView, index: 05, animated: false)
        setScrollViewPosition(secondScrollView, index: 05, animated: false)
        
        // 更新单位标签位置
        updateUnitLabelsPosition()
    }
    
    private func setScrollViewPosition(_ scrollView: UIScrollView, index: Int, animated: Bool) {
        let yOffset = CGFloat(index) * rowHeight - (scrollView.bounds.height - rowHeight) / 2
        scrollView.setContentOffset(CGPoint(x: 0, y: yOffset), animated: animated)
    }
    
    private func updateUnitLabelsPosition() {
        // 计算选中行中心位置
        let centerY = bounds.height / 2
        
        // 更新单位标签位置
        hourUnitLabel.frame = CGRect(
            x: hourScrollView.frame.maxX - 25,
            y: centerY - 10,
            width: 20,
            height: 20
        )
        
        minuteUnitLabel.frame = CGRect(
            x: minuteScrollView.frame.maxX - 25,
            y: centerY - 10,
            width: 20,
            height: 20
        )
        
        secondUnitLabel.frame = CGRect(
            x: secondScrollView.frame.maxX - 25,
            y: centerY - 10,
            width: 20,
            height: 20
        )
        
        // 显示单位标签
        hourUnitLabel.isHidden = false
        minuteUnitLabel.isHidden = false
        secondUnitLabel.isHidden = false
    }
    
    // MARK: - 公共方法
    func setTime(hour: Int, minute: Int, second: Int) {
        selectedHour = hour
        selectedMinute = minute
        selectedSecond = second
        
        // 更新滚动视图位置
        let hourIndex = hour == -1 ? hours.count - 1 : (hour < hours.count - 1 ? hour : hours.count - 1)
        setScrollViewPosition(hourScrollView, index: hourIndex, animated: true)
        setScrollViewPosition(minuteScrollView, index: minute, animated: true)
        setScrollViewPosition(secondScrollView, index: second, animated: true)
        
        // 更新标签样式
        updateLabelsStyle()
    }
    
    func getTime() -> (hour: Int, minute: Int, second: Int) {
        return (selectedHour, selectedMinute, selectedSecond)
    }
    
    // MARK: - 私有方法
    private func updateLabelsStyle() {
        // 更新所有标签样式
        updateLabelStyle(for: hourLabels, selectedIndex: getSelectedIndex(from: hourScrollView))
        updateLabelStyle(for: minuteLabels, selectedIndex: getSelectedIndex(from: minuteScrollView))
        updateLabelStyle(for: secondLabels, selectedIndex: getSelectedIndex(from: secondScrollView))
    }
    
    private func updateLabelStyle(for labels: [UILabel], selectedIndex: Int) {
        for (index, label) in labels.enumerated() {
            if index == selectedIndex {
                // 选中行样式
                label.font = UIFont.systemFont(ofSize: 30, weight: .semibold)
                label.textColor = HexRGB(0x3d4466)
                label.transform = CGAffineTransform(scaleX: 1.2, y: 1.2)
            } else {
                // 非选中行样式
                let chazhi = abs(selectedIndex - index);
                if chazhi <= 4 {
                    label.font = UIFont.systemFont(ofSize: CGFloat(20 - chazhi*2), weight: .regular)
                }else{
                    label.font = UIFont.systemFont(ofSize: CGFloat(12), weight: .regular)
                }
                label.textColor = .lightGray
                label.transform = .identity
            }
        }
    }
    private func getSelectedIndex(from scrollView: UIScrollView) -> Int {
        let offsetY = scrollView.contentOffset.y + (scrollView.bounds.height - rowHeight) / 2
        let index = Int(round(offsetY / rowHeight))
        return max(0, min(index, scrollView == hourScrollView ? hours.count - 1 : 59))
    }
    
    private func snapToNearestRow(_ scrollView: UIScrollView) {
        let offsetY = scrollView.contentOffset.y + (scrollView.bounds.height - rowHeight) / 2
        let index = Int(round(offsetY / rowHeight))
        
        // 限制索引范围
        let maxIndex = scrollView == hourScrollView ? hours.count - 1 : 59
        let clampedIndex = max(0, min(index, maxIndex))
        
        setScrollViewPosition(scrollView, index: clampedIndex, animated: true)
        
        // 更新选中值
        if scrollView == hourScrollView {
            selectedHour = clampedIndex == hours.count - 1 ? -1 : clampedIndex
        } else if scrollView == minuteScrollView {
            selectedMinute = clampedIndex
        } else if scrollView == secondScrollView {
            selectedSecond = clampedIndex
        }
        
        // 更新标签样式
        updateLabelsStyle()
        
        // 触发回调
        onTimeChanged?(selectedHour, selectedMinute, selectedSecond)
    }
}

// MARK: - UIScrollViewDelegate
extension CustomTimePickerView: UIScrollViewDelegate {
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        updateLabelsStyle()
    }
    
    func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        if !decelerate {
            snapToNearestRow(scrollView)
        }
    }
    
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        snapToNearestRow(scrollView)
    }
}

